﻿using System;
using System.Web.UI.WebControls;
using Team4Mock.Entity;
using System.Linq;
using System.Data;
namespace Team4Mock.UserControl.Premise
{
    public partial class ListAll : System.Web.UI.UserControl
    {
        PremiseEntity pe=new PremiseEntity();
        OrganisationEntity oe = new OrganisationEntity();
        ServiceEntity se=new ServiceEntity();
        ServicePremiseEntities sp=new ServicePremiseEntities();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //if (!string.IsNullOrEmpty(Convert.ToString(Session["role"])))
                //{
                //    if (Session["role"].ToString().Equals("Admin"))
                //    {
                        if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["ID"])))
                        {
                            pnAdd.Visible = false;
                            pnView.Visible = true;
                            pnAmend.Visible = false;
                            
                            gvPremise.DataSource = pe.Getdata();
                            gvPremise.DataBind();
                        }
                        else
                        {
                            try
                            {

                                int id = int.Parse(Request.QueryString["ID"]);
                                sp.PreId = id;
                                gvService.DataSource = sp.GetPremiseService(sp);
                                gvService.DataBind();
                                pe.PremisesID = id;
                                pnAdd.Visible = false;
                                pnView.Visible = false;
                                pnAmend.Visible = true;
                                GridView1.DataSource = sp.PreSer_GetSer(sp);
                                GridView1.DataBind();
                                dlCountry.DataSource = oe.GetCountry();
                                dlCountry.DataBind();
                                GetCheckboxList(pe.GetAcc(), pe.GetAccById(pe), clAcc);
                                GetCheckboxList(pe.GetJcpOff(), pe.GetJcpById(pe), clJcpOff);
                                GetCheckboxList(pe.GetLocDem(), pe.GetLocDemById(pe), clLocDemoIss);
                                GetCheckboxList(pe.GetLocHot(), pe.GetLocHotById(pe), clLocHot);
                                GetCheckboxList(pe.GetLocTyp(), pe.GetLocTypById(pe), clLocTyp);
                                GetCheckboxList(pe.GetOutLoc(), pe.GetOutLocById(pe), clOutLoc);
                                dlCateType.DataSource = pe.GetCatTyp();
                                dlCateType.DataBind();
                                GetdataByID();
                            }
                            catch
                            {
                                Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "Error();", true);
                            }
                        }
                //    }
                //    else
                //    {
                //        Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "Rediect();", true);
                //    }
                //}
                //else
                //{
                //    Response.Redirect("/FormView/Login.aspx");
                //}
            }
        }
        void GetCheckboxList(DataTable dt1, DataTable dt2, CheckBoxList cl)
        {
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                cl.Items.Add(new ListItem(dt1.Rows[i][1].ToString(), dt1.Rows[i][0].ToString()));
            }
            //Get ID
            for (int j = 0; j < cl.Items.Count; j++)
            {
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    if (dt2.Rows[i][0].ToString().Equals(cl.Items[j].Value))
                    {
                        cl.Items[j].Selected = true;
                    }
                }
            }
        }

        void GetdataByID()
        {
            int id = int.Parse(Request.QueryString["ID"]);
            pe.PremisesID = id;
            DataTable dt = new DataTable();
            dt = pe.GetDataByIdP(pe);
            if (dt.Rows.Count > 0)
            {
                txtLocName.Text = dt.Rows[0][1].ToString();
                txtKnowAs.Text = dt.Rows[0][2].ToString();
                dlLocSta.SelectedValue = dt.Rows[0][3].ToString();
                txtLocStaDate.Text = dt.Rows[0][4].ToString();
                txtAdd1.Text = dt.Rows[0][5].ToString();
                txtAdd2.Text = dt.Rows[0][6].ToString();
                txtAdd3.Text = dt.Rows[0][7].ToString();
                PostCode.Value = dt.Rows[0][8].ToString();
                Town.Value = dt.Rows[0][9].ToString();
                County.Value = dt.Rows[0][10].ToString();
                dlCountry.SelectedValue = dt.Rows[0][11].ToString();
                ckPriLoc.Checked = dt.Rows[0][12].ToString().Equals("1") ? true : false;
                ckLocMan.Checked = dt.Rows[0][13].ToString().Equals("1") ? true : false;
                ckSTNetCon.Checked = dt.Rows[0][14].ToString().Equals("1") ? true : false;
                txtDesFull.Text = dt.Rows[0][15].ToString();
                txtPhone.Text = dt.Rows[0][16].ToString();
                txtGerNum.Text = dt.Rows[0][17].ToString();
                txtMiniNum.Text = dt.Rows[0][18].ToString();
                ckIsNewShop.Checked = dt.Rows[0][19].ToString().Equals("1") ? true : false;
                txtShopFlagDate.Text = dt.Rows[0][20].ToString();
                ckSpecShop.Checked = dt.Rows[0][21].ToString().Equals("1") ? true : false;
                ckMediaContact.Checked = dt.Rows[0][22].ToString().Equals("1") ? true : false;
                idMediaContact.Value = dt.Rows[0][23].ToString();
                txtLocDemNotes.Text = dt.Rows[0][24].ToString();
                ckCateFac.Checked = dt.Rows[0][25].ToString().Equals("1") ? true : false;
                idCatering.Value = dt.Rows[0][26].ToString();
                dlCateType.SelectedValue = dt.Rows[0][27].ToString();
                dlISNetwork.SelectedValue = dt.Rows[0][28].ToString();
                ckClientIFFac.Checked = dt.Rows[0][29].ToString().Equals("1") ? true : false;
                txtClientFacDetails.Text = dt.Rows[0][30].ToString();
                ckRoomAvai.Checked = dt.Rows[0][31].ToString().Equals("1") ? true : false;
                ckVolunOpp.Checked = dt.Rows[0][32].ToString().Equals("1") ? true : false;
                txtTravelDetail.Text = dt.Rows[0][33].ToString();
                txtTravelBus.Text = dt.Rows[0][34].ToString();
                txtTravelRail.Text = dt.Rows[0][35].ToString();
                txtTravelAirport.Text = dt.Rows[0][36].ToString();
                ckHostVisit.Checked = dt.Rows[0][37].ToString().Equals("1") ? true : false;
                idhostingcontact.Value = dt.Rows[0][38].ToString();
                ckVisitParkOnsite.Checked = dt.Rows[0][39].ToString().Equals("1") ? true : false;
                txtVisitParkSpac.Text = dt.Rows[0][40].ToString();
                txtVisitParkingAlt.Text = dt.Rows[0][41].ToString();
                txtRoomrate.Text = dt.Rows[0][42].ToString();
                txtBBRate.Text = dt.Rows[0][43].ToString();
                txtDDRate.Text = dt.Rows[0][44].ToString();
                txtHrRate.Text = dt.Rows[0][45].ToString();
                txtTeaAndCoffee.Text = dt.Rows[0][46].ToString();
                ckLunch.Checked = dt.Rows[0][47].ToString().Equals("1") ? true : false;
                txtNoMeetingRoom.Text = dt.Rows[0][48].ToString();
                txtMeetingRoomPerDay.Text = dt.Rows[0][49].ToString();
                dlCodings.SelectedValue = dt.Rows[0][50].ToString();
                txtNegoRoom.Text = dt.Rows[0][51].ToString();
                txtBBNego.Text = dt.Rows[0][52].ToString();
                txtDBBNego.Text = dt.Rows[0][53].ToString();
                txtDDNego.Text = dt.Rows[0][54].ToString();
                txtHrNego.Text = dt.Rows[0][55].ToString();
                txtLastNego.Text = dt.Rows[0][56].ToString();
                txtReNego.Text = dt.Rows[0][57].ToString();
                dlPrefrred.SelectedValue = dt.Rows[0][58].ToString();
                txtComments.Text = dt.Rows[0][59].ToString();
                idOrg.Value = dt.Rows[0][60].ToString();
                ckactive.Checked = dt.Rows[0][61].ToString().Equals("Yes") ? true : false;
            }
        }
        protected void btnCreate_Click(object sender, EventArgs e)
        {
            pnAdd.Visible = true;
            pnView.Visible = false;
            pnAmend.Visible = false;
        }

        public SortDirection SortDirection
        {
            get
            {
                if (ViewState["SortDirection"] == null)
                {
                    ViewState["SortDirection"] = SortDirection.Ascending;
                }
                return (SortDirection)ViewState["SortDirection"];
            }
            set
            {
                ViewState["SortDirection"] = value;
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("/FormView/Premise.aspx");
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //Amend
            Label1.Text = "";
            if (txtPhone.Text == "")
            {
                Label1.Text += "Input Phone Number" + "</br>";
            }
            if (idOrg.Value == "")
            {
                Label1.Text += "Select Organization";
            }
            if (txtLocName.Text == "")
            {
                Label1.Text += "Input Location Name" + "</br>";
            }
            if (ckClientIFFac.Checked==true)
            {
                Label1.Text += "Input Client IT Facility Details" + "</br>";
            }
            if (ckVisitParkOnsite.Checked == true)
            {
                Label1.Text += "Input Visitor Parking Spaces" + "</br>";
            }
            if (dlLocSta.SelectedIndex == 0)
            {
                Label1.Text += "Select Location Status" + "</br>";
            }
            if (PostCode.Value == "")
            {
                Label1.Text += "Select Post Code" + "</br>";
            }
            if (ckMediaContact.Checked == true)
            {
                if (idMediaContact.Value == "")
                {
                    Label1.Text += "Select Media Contact" + "</br>";
                }
            }
            if (ckCateFac.Checked == true)
            {
                if (idCatering.Value == "")
                {
                    Label1.Text += "Select Catering Contact" + "</br>";
                }
            }
            if (ckHostVisit.Checked == true)
            {
                if (idhostingcontact.Value == "")
                {
                    Label1.Text += "Select Hosting Contact" + "</br>";
                }
            }
            //neu da nhap het
            if (Label1.Text == "")
            {
                if (UpdatePremise() == true)
                {
                    try
                    {
                        GetValueCheckBoxList(clAcc, "Acc");
                        GetValueCheckBoxList(clJcpOff, "Jcp");
                        GetValueCheckBoxList(clLocDemoIss, "LocDem");
                        GetValueCheckBoxList(clLocHot, "LocHot");
                        GetValueCheckBoxList(clLocTyp, "LocTyp");
                        GetValueCheckBoxList(clOutLoc, "OutLoc");
                        Label1.Text = "Update Premise successfuly";
                    }
                    catch(Exception a)
                    {
                        Label1.Text = a.Message;
                    }
                }
                else
                {
                    Label1.Text = err;
                }
            }
            else
            {
                Label1.Text +="!";
            }
        }
        private DataTable dt;
        protected void All_Click(object sender, EventArgs e)
        {
            ViewState.Remove("sortkey");
            dt = pe.Getdata();
            if (dt.Rows.Count > 0)
            {
                gvPremise.DataSource = dt;
                gvPremise.DataBind();
                abc.Text = "";
            }
            else
            {
                abc.Text = "No Record";
            }
        }

        private string err;
        bool UpdatePremise()
        {
            try
            {
                string idorg = idOrg.Value;
                string postcode = PostCode.Value;
                string town = Town.Value;
                string county = County.Value;
                string idmedia = idMediaContact.Value;
                string idcatering = idCatering.Value;
                string idhosting = idhostingcontact.Value;

                pe.LocationName = txtLocName.Text;
                pe.KnowAs = txtKnowAs.Text;
                pe.Organizationid = int.Parse(idorg);
                pe.LocationStatus = dlLocSta.SelectedValue;
                pe.LocationStatusDate = txtLocStaDate.Text;// DateTime.Parse(txtLocStaDate.Text);
                pe.AddressLine1 = txtAdd1.Text;
                pe.AddressLine2 = txtAdd2.Text;
                pe.AddressLine3 = txtAdd3.Text;
                pe.PostCode = postcode;
                pe.Town = town;
                pe.County = county;
                pe.Country = dlCountry.SelectedValue;
                pe.PrimaryLocation = ckPriLoc.Checked ? 1 : 0;
                pe.LocationManaged = ckLocMan.Checked ? 1 : 0;
                pe.STNetworkConectivity = ckSTNetCon.Checked ? 1 : 0;
                pe.LocationDescription = txtDesFull.Text;
                pe.PhonNumber = txtPhone.Text;
                pe.GeneralFaxNumber = txtGerNum.Text;
                pe.MinicommNumber = txtMiniNum.Text;
                pe.IsNewShop = ckIsNewShop.Checked ? 1 : 0;
                pe.ShopFlagDate = txtShopFlagDate.Text;// DateTime.Parse(txtShopFlagDate.Text);
                pe.SpecialistShop = ckSpecShop.Checked ? 1 : 0;
                pe.MediaContact = ckMediaContact.Checked ? 1 : 0;
                pe.MediaContactName = ckMediaContact.Checked ? idmedia : "";
                pe.LocalDemographicNotes = txtLocDemNotes.Text;
                pe.CateringFacilities = ckCateFac.Checked ? 1 : 0;
                pe.CateringContact = ckCateFac.Checked ? idcatering : "";
                pe.CateringType = dlCateType.SelectedValue;
                pe.ISNetwork = dlISNetwork.SelectedValue;
                pe.ClientITFacilities = ckClientIFFac.Checked ? 1 : 0;
                pe.ClientITFacilitiesDetail = ckClientIFFac.Checked ? txtClientFacDetails.Text : "";
                pe.RoomAvailability = ckRoomAvai.Checked ? 1 : 0;
                pe.VolunteeringOpportunities = ckVolunOpp.Checked ? 1 : 0;
                pe.TravelDetail = txtTravelDetail.Text;
                pe.TravelNearestBus = txtTravelBus.Text;
                pe.TravelNearestRail = txtTravelRail.Text;
                pe.TravelNearestAirport = txtTravelBus.Text;
                pe.HostVisits = ckHostVisit.Checked ? 1 : 0;
                pe.HostingContact = ckHostVisit.Checked ? idhosting : "";
                pe.VisitorParkingOnsite = ckVisitParkOnsite.Checked ? 1 : 0;
                pe.VisitorParkingSpaces = ckVisitParkOnsite.Checked ? txtVisitParkSpac.Text : "";
                pe.VisitorParkingAltemnative = txtVisitParkingAlt.Text;
                pe.RoomOnlyRate = txtRoomrate.Text;
                pe.BAndBRate = txtBBRate.Text;
                pe.DBBRate = txtDBBRate.Text;
                pe.DDRate = txtDDRate.Text;
                pe.HrRate = txtHrRate.Text;
                pe.TeaAndCoffe = txtTeaAndCoffee.Text;
                pe.Lunch = ckLunch.Checked ? 1 : 0;
                pe.NoOfMeetingRooms = txtNoMeetingRoom.Text;
                pe.MeetingRoomRatePerDay = txtMeetingRoomPerDay.Text;
                pe.Codings = dlCodings.SelectedValue;
                pe.NegotiatedRoomOnlyRate = txtNegoRoom.Text;
                pe.BBNegotiatedRate = txtBBNego.Text;
                pe.DBBNegotiatedRate = txtDBBRate.Text;
                pe.DDNegotiatedRate = txtDDNego.Text;
                pe.HrNegotiatedRate = txtHrNego.Text;
                pe.LastNegotiatedRate = txtLastNego.Text;//DateTime.Parse(txtLastNego.Text);
                pe.ReNegotiateOn = txtReNego.Text;// DateTime.Parse(txtReNego.Text);
                pe.PreferredStatus = dlPrefrred.SelectedValue;
                pe.Comments = txtComments.Text;
                pe.PremisesID = int.Parse(Request.QueryString["ID"]);
                pe.IsActive = ckactive.Checked ? 1 : 0;
                pe.Update(pe);

                return true;
            }
            catch (Exception e)
            {
                err = e.Message;
                return false;
            }
        }

        void GetValueCheckBoxList(CheckBoxList cl, string table)
        {
            try
            {
                int id = int.Parse(Request.QueryString["ID"]);
                pe.PremisesID = id;

                string lb = string.Empty;
                for (int i = 0; i < cl.Items.Count; i++)
                {
                    if (cl.Items[i].Selected == true)
                    {
                        lb += cl.Items[i].Value + "=";
                    }
                }
                string[] tmp = lb.Split('=');
                switch (table)
                {
                    case "Acc":
                        {
                            pe.DelAcc(pe);
                            for (int i = 0; i < tmp.Count() - 1; i++)
                            {
                                pe.RefID = int.Parse(tmp[i].ToString());
                                pe.InsertAcc(pe);
                            }
                        }
                        break;
                    case "Jcp":
                        {
                            pe.DelJcpOff(pe);
                            for (int i = 0; i < tmp.Count() - 1; i++)
                            {
                                pe.RefID = int.Parse(tmp[i].ToString());
                                pe.InsertJcpOff(pe);
                            }
                        }
                        break;
                    case "LocDem":
                        {
                            pe.DelLocDem(pe);
                            for (int i = 0; i < tmp.Count() - 1; i++)
                            {
                                pe.RefID = int.Parse(tmp[i].ToString());
                                pe.InsertLocDem(pe);
                            }
                        }
                        break;
                    case "LocHot":
                        {
                            pe.DelLocHot(pe);
                            for (int i = 0; i < tmp.Count() - 1; i++)
                            {
                                pe.RefID = int.Parse(tmp[i].ToString());
                                pe.InsertLocHot(pe);
                            }
                        }
                        break;
                    case "LocTyp":
                        {
                            pe.DelLocTyp(pe);
                            for (int i = 0; i < tmp.Count() - 1; i++)
                            {
                                pe.RefID = int.Parse(tmp[i].ToString());
                                pe.InsertLocTyp(pe);
                            }
                        }
                        break;
                    case "OutLoc":
                        {
                            pe.DelOutLoc(pe);
                            for (int i = 0; i < tmp.Count() - 1; i++)
                            {
                                pe.RefID = int.Parse(tmp[i].ToString());
                                pe.InsertOutLoc(pe);
                            }
                        }
                        break;
                }
            }
            catch
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "Error();", true);
            }

        }
        protected void LinkButton2_Click(object sender, EventArgs e)
        {
            ViewState["sortkey"] = "ABCDE";
            pe.Key = "ABCDE";
            dt = pe.Search(pe);
            if (dt.Rows.Count > 0)
            {
                gvPremise.DataSource = dt;
                gvPremise.DataBind();
                abc.Text = "";
            }
            else
            {
                ViewState.Remove("sortkey");
                abc.Text = "No Record";
            }
        }

        protected void LinkButton3_Click(object sender, EventArgs e)
        {
            ViewState["sortkey"] = "FGHIJ";
            pe.Key = "FGHIJ";
            dt = pe.Search(pe);
            if (dt.Rows.Count > 0)
            {
                gvPremise.DataSource = dt;
                gvPremise.DataBind();
                abc.Text = "";
            }
            else
            {
                ViewState.Remove("sortkey");
                abc.Text = "No Record";
            }
        }

        protected void LinkButton4_Click(object sender, EventArgs e)
        {
            ViewState["sortkey"] = "KMNL";
            pe.Key = "KMNL";
            dt = pe.Search(pe);
            if (dt.Rows.Count > 0)
            {
                gvPremise.DataSource = dt;
                gvPremise.DataBind();
                abc.Text = "";
            }
            else
            {
                ViewState.Remove("sortkey");
                abc.Text = "No Record";
            }
        }

        protected void LinkButton5_Click(object sender, EventArgs e)
        {
            ViewState["sortkey"] = "OPQR";
            pe.Key = "OPQR";
            dt = pe.Search(pe);
            if (dt.Rows.Count > 0)
            {
                gvPremise.DataSource = dt;
                gvPremise.DataBind();
                abc.Text = "";
            }
            else
            {
                ViewState.Remove("sortkey");
                abc.Text = "No Record";
            }
        }

        protected void LinkButton6_Click(object sender, EventArgs e)
        {
            ViewState["sortkey"] = "STUV";
            pe.Key = "STUV";
            dt = pe.Search(pe);
            if (dt.Rows.Count > 0)
            {
                gvPremise.DataSource = dt;
                gvPremise.DataBind();
                abc.Text = "";
            }
            else
            {
                ViewState.Remove("sortkey");
                abc.Text = "No Record";
            }
        }

        protected void LinkButton7_Click(object sender, EventArgs e)
        {
            ViewState["sortkey"] = "WXYZ";
            pe.Key = "WXYZ";
            dt = pe.Search(pe);
            if (dt.Rows.Count > 0)
            {
                gvPremise.DataSource = dt;
                gvPremise.DataBind();
                abc.Text = "";
            }
            else
            {
                ViewState.Remove("sortkey");
                abc.Text = "No Record";
            }
        }

        protected void gvPremise_Sorting(object sender, System.Web.UI.WebControls.GridViewSortEventArgs e)
        {

            DataTable dt = new DataTable();
            if (ViewState["sortkey"] != null)
            {
                string sortkey = ViewState["sortkey"].ToString();
                pe.Key = sortkey;
                if (CheckBox1.Checked == true)
                {
                    dt = pe.Search(pe);
                }
                else
                {
                    dt = pe.SearchTrue(pe);
                }
            }
            else
            {
                dt = CheckBox1.Checked ? pe.Getdata(): pe.GetdataTrue();
            }

            string sortExpression = e.SortExpression;
            string direction = string.Empty;
            string sort = "";
            if (SortDirection == SortDirection.Ascending)
            {
                SortDirection = SortDirection.Descending;
                direction = " DESC";
                sort = "↑";
            }
            else
            {
                SortDirection = SortDirection.Ascending;
                direction = " ASC";
                sort = "↓";
            }
            if (sortExpression == "LocationName")
            {
                gvPremise.Columns[1].HeaderText = "Location Name " + sort;
                gvPremise.Columns[2].HeaderText = "Head Office Address Line 1";
                gvPremise.Columns[3].HeaderText = "Post Code";
            }
            if (sortExpression == "AddressLine1")
            {
                gvPremise.Columns[1].HeaderText = "Location Name";
                gvPremise.Columns[2].HeaderText = "Head Office Address Line 1 " + sort;
                gvPremise.Columns[3].HeaderText = "Post Code";
            }
            if (sortExpression == "PostCode")
            {
                gvPremise.Columns[1].HeaderText = "Location Name";
                gvPremise.Columns[2].HeaderText = "Head Office Address Line 1";
                gvPremise.Columns[3].HeaderText = "Post Code " + sort;
            }
            dt.DefaultView.Sort = sortExpression + direction;

            gvPremise.DataSource = dt;
            gvPremise.DataBind();
        }

        protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (ViewState["sortdirec"] != null)
            {
                string sort = ViewState["sortdirec"].ToString();
                pe.Key = sort;
                if (CheckBox1.Checked == true)
                {
                    gvPremise.DataSource = pe.Search(pe);
                    gvPremise.DataBind();
                }
                else
                {
                    gvPremise.DataSource = pe.SearchTrue(pe);
                    gvPremise.DataBind();
                }
            }
            else
            {
                if (CheckBox1.Checked == true)
                {
                    gvPremise.DataSource = pe.Getdata();
                    gvPremise.DataBind();
                }
                else
                {

                    gvPremise.DataSource = pe.GetdataTrue();
                    gvPremise.DataBind();
                }
            }
        }

        protected void gvService_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Remove")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                //tbao.Text = index.ToString();
            }
        }

  
       
    }
}